package com.lucas.shopping.seckill.web;

import com.alibaba.fastjson.JSONObject;
import com.lucas.shopping.config.Constants;
import com.lucas.shopping.seckill.entity.Product;
import com.lucas.shopping.seckill.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.print.attribute.standard.Media;
import java.util.ArrayList;
import java.util.List;

@RestController
@RefreshScope
@RequestMapping("/seckill")
@Slf4j
public class SecKillController {





    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    @Qualifier("seckillProduct")
    private DefaultRedisScript<Long> defaultRedisScript;

    @Autowired
    private ProductService productService;

    /**
     * 设置库存
     * @return
     */
    @PostMapping(value = "/postProductStock",produces = MediaType.APPLICATION_JSON_VALUE)
    public String postProductStock(@RequestParam("code") Long id){
        Product product =  productService.getById(id);
        redisTemplate.opsForValue().set(Constants.redis_product_key_prefix+id,product.getStock());
        return "success";
    }

    /**
     * 插入商品
     */
    @PostMapping(value = "/saveProduct",produces = MediaType.APPLICATION_JSON_VALUE)
    public String saveProduct(Product product){
        productService.save(product);
        return "success";
    }


    /**
     * 秒杀接口
     * @param code
     * @param userId
     * 采用Redis Lua脚本控制秒杀
     * @return
     */
    @PostMapping(value = "seckillProduct",produces = MediaType.APPLICATION_JSON_VALUE)
    public JSONObject seckillProduct(@RequestParam("code") String code, @RequestParam("userId") String userId){
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("code",0);
        rtnJson.put("msg","ok");
        List<String> keys = new ArrayList<>();
        keys.add(Constants.redis_product_key_prefix+code);
        keys.add(Constants.redis_product_key_prefix+code+":"+userId);
        Long i  = redisTemplate.execute(defaultRedisScript, keys);
        if(i!=1L){
            log.info(i.toString());
            rtnJson.put("msg","库存不足");
        }

        return rtnJson;
    }
}



